// * Input组件
<template>
  <input
    type="text"
    :value="currentValue"
    @input="handleInput"
    @blur="handleBlur"
  />
</template>

<script>
import Emitter from '../../mixins/emitter'

export default {
  name: 'Input',

  mixins: [Emitter],

  props: {
    value: {
      type: String,
      default: '',
    },
  },

  computed: {
    currentValue: {
      get() {
        return this.value
      },
      set(text) {
        this.$emit('input', text)
      },
    },
  },

  watch: {
    value(val) {
      this.currentValue = val
    },
  },

  methods: {
    handleInput(e) {
      const value = e.target.value
      this.currentValue = value

      this.notifyUser({ type: 'input', data: value })

      this.notifyFormItem({ type: 'change', data: value })
    },

    handleBlur(e) {
      this.notifyFormItem({ type: 'blur', data: this.currentValue })
    },

    // * 通知用户组件(对用户开放的时间接口)
    notifyUser({ type, data }) {
      switch (type) {
        case 'input':
          this.$emit('on-input', data) // 对用户开放on-change
          break
      }
    },

    // * 通知FormItem组件
    notifyFormItem({ type, data }) {
      switch (type) {
        case 'change':
          this.dispatch('FormItem', 'on-form-change', data)
          break
        case 'blur':
          this.dispatch('FormItem', 'on-form-blur', data)
          break
      }
    },
  },
}
</script>
